package com.szzg10.webservice.chapter1;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyThreadPool extends ThreadPoolExecutor {

	private static final int pool_size = 10;
	private boolean is_paused;
	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	public MyThreadPool() {
		super(pool_size, pool_size, 0l, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(pool_size));
	}
	
	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		
		super.beforeExecute(t, r);
		lock.lock();
		try {
			while(is_paused) {
				condition.await();
			}
		}
		catch(InterruptedException e) {
			t.interrupt();
		}
		finally {
			lock.unlock();
		}
	}
	
	public void pause() {
		
		lock.lock();
		try {
			is_paused = true;
		}
		finally {
			lock.unlock();
		}
	}
	
	public void resume() {
		
		lock.lock();
		try {
			is_paused = false;
			condition.signalAll();
		}
		finally {
			lock.unlock();
		}
	}
}
